import Rx from "rxjs"
import "../myjQuery";

// 使用rxjs来模拟输入框的校验
// 第一次输入的时候只对最大长度进行校验，失去焦点以后对最小长度和必填进行校验

let input = document.querySelector("#myInput");
let inputObservable = Rx.Observable.fromEvent(input, "input");
let inputBlurObservable = Rx.Observable.fromEvent(input, "blur");
let resetObservable = Rx.Observable.fromEvent(document.querySelector("#resetBtn"), "click");

let validatorSubcription;
let haveBeenTouched = false;

resetObservable.throttleTime(200)
    .subscribe(event => {
        input.value = "";
        console.log("reset value.")
    });

inputBlurObservable.subscribe((event) => {
    console.log("blur");
    haveBeenTouched = true;
    if(!validateAfterBlur(event.target.value)){
        console.log("error:after blur");
    }
})

inputObservable.subscribe(event => {
    if (!validateWhileInput(event.target.value)) {
        console.log("error:inputing");
        return;
    }
    if (haveBeenTouched && !validateAfterBlur(event.target.value)) {
        console.log("error:after blur")
        return;
    }
    console.log("success");
})

let validateWhileInput = (value) => {
    if (value.length > 10) {
        console.log("the length of value is:" + value.length);
        return false;
    }
    if (value.indexOf("#") != -1) {
        console.log("the value contain #");
        return false;
    }
    return true;
};

let validateAfterBlur = (value) => {
    if (value.length < 3) {
        console.log("the length of value is:" + value.length);
        return false;
    }
    return true;
}